package c.x.jy.common.utils;


import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;

import c.x.jy.common.exception.RRException;
 

/**
 * 阿里云短信工具类
 * <p>
 * 目前templateCode已设为：SMS_32705015
 *
 * @author Linch
 */
@SuppressWarnings("all")
public class SMSUtil {
	
	/*public SMSUtil(String accessKeyId ,String accessKeySecret,String signName,String mode){
		this.accessKeyId=accessKeyId;
		this.accessKeySecret=accessKeySecret;
		this.signName=signName;
		this.mode=mode;
	}*/

  // private static String accessKeyId = "LTAIStrOEqKopj7i";
   // private static  String accessKeySecret = "RRoiiz5qYLpnnBA5uezQ9azcaTBjfK";
   // private static String signName = "前海嘉园";
    private final static String product = "Dysmsapi";//短信API产品名称（短信产品名固定，无需修改）
    private final static String domain = "dysmsapi.aliyuncs.com";//短信API产品域名（接口地址固定，无需修改）
    
  //  private static String mode;
    
   // private static Map<String ,String> map=new HashMap<String ,String> ();

  /*  
 static{
		map.put("reg", "SMS_140850039");
		map.put("notes", "SMS_140726817");
		//设备异常
		map.put("notes1", "SMS_141581126");
  }
  *

   /* @Value("${sms.accessKeyId}")
    public  void setAccessKeyId(String accessKeyId) {
		SMSUtil.accessKeyId = accessKeyId;
	}
    @Value("${sms.accessKeySecret}")
	public  void setAccessKeySecret(String accessKeySecret) {
		SMSUtil.accessKeySecret = accessKeySecret;
	}
    @Value("${sms.signName}")
	public  void setSignName(String signName) {
		SMSUtil.signName = signName;
	}*/
   /* @Value("${sms.templatecode.reg}")
    public void setTemplate(String template){
    	map.put("reg", "SMS_140850039");
    }
    @Value("${sms.templatecode.notes}")
    public void setTemplate1(String template){
    	map.put("notes", "SMS_140726817");
    }
    */

	/**
     * 发送短信
     *
     * @param phoneNo      手机号码
     * @param templateCode 模板CODE
     * @param params       参数
     */
    private static  boolean send(String phoneNo, String templateCode, String signName, Map<String, String> params,String accessKeyId,String accessKeySecret) {
      //  Map<String, String> ret = new HashMap<String, String>();
    	 SendSmsResponse sendSmsResponse=null;
    	    IAcsClient acsClient=null;
        if (StringUtils.isEmpty(phoneNo)) {
            throw new RRException("发送失败，手机号码为空!");
        }
        if (StringUtils.isEmpty(templateCode)) {
            throw new RRException("发送失败，未找到该模板");
        }
        try {
            IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
                    accessKeySecret);
            DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain);
             acsClient = new DefaultAcsClient(profile);
            //组装请求对象
            SendSmsRequest request = new SendSmsRequest();
            //使用post提交
            request.setMethod(MethodType.POST);
            //必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式；发送国际/港澳台消息时，接收号码格式为00+国际区号+号码，如“0085200000000”
            request.setPhoneNumbers(phoneNo);
            //必填:短信签名-可在短信控制台中找到
            request.setSignName(signName);
            //必填:短信模板-可在短信控制台中找到
            request.setTemplateCode(templateCode);
            //可选:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为
            //友情提示:如果JSON中需要带换行符,请参照标准的JSON协议对换行符的要求,比如短信内容中包含\r\n的情况在JSON中需要表示成\\r\\n,否则会导致JSON在服务端解析失败
            request.setTemplateParam(JSON.toJSONString(params));
            //可选-上行短信扩展码(扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段)
            //request.setSmsUpExtendCode("90997");
            //可选:outId为提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者
            //请求失败这里会抛ClientException异常
             sendSmsResponse = acsClient.getAcsResponse(request);
             System.out.println(JSON.toJSONString(sendSmsResponse));
            return sendSmsResponse.getCode() != null && sendSmsResponse.getCode().equals("OK");
        } catch (ClientException e) {
            e.printStackTrace();
        }finally {
        	
       	sendSmsResponse=null;
        	acsClient=null;
		}
        return true;
    }

    public static  boolean send(String phone, String templateCode, Map<String, String> params,SmsConfig smsConfig) {
    	System.out.println(smsConfig.getSmsSignName());
    	return send(phone, templateCode, smsConfig.getSmsSignName(), params, smsConfig.getSmsAccessKeyId(), smsConfig.getSmsAccessKeySecret() );
    }

    /**
     * 发送注册短信
     * @param phone
     * @return
     */
    public static String sendByRegister(String phone,SmsConfig smsConfig) {
        Map<String, String> params = new HashMap<>();
        Random rand = new Random();
        String code = String.format("%05d",rand.nextInt(99999));
        params.put("code",code);
         if (send(phone, smsConfig.getSmsRegcode(),params,smsConfig)){
             return code;
         }else{
             return null;
         }
    }

    
    
    public static String sendByRegister(String phone,String templateCode, String signName,String accessKeyId,String accessKeySecret) {
        Map<String, String> params = new HashMap<>();
        Random rand = new Random();
        String code = String.format("%05d",rand.nextInt(99999));
        params.put("code",code);
         if (send(phone, templateCode,signName,params,accessKeyId,accessKeySecret)){
             return code;
         }else{
             return null;
         }
    }
    
    /**
     * 
     * @param phone  待发送的手机号码
     * @param userName 用户名
     * @param devceName 设备名
     * @param count   剩余数量
     * @return
     */
    public static boolean sendByNotes(String phone,String userName,String deviceName,String count,SmsConfig smsConfig){
    	   Map<String, String> params = new HashMap<>();
    	   params.put("name", userName);
    	   params.put("devicename", deviceName);
    	   params.put("count", count);
    	
    	return send(phone,smsConfig.getSmsNotescode(),params,smsConfig);
    }
    
    

    
    
    
 /*   public static void main(String args[]) throws IOException {
        Map<String, String> map = new HashMap<>();
        map.put("product", "绑定微信服务号");
        map.put("code", "23623");
        SMSUtil.send("18607337285", "SMS_32705015", map);
        SMSUtil.sendByRegister("18607337285");
    }*/
    /**
     * 发送设备异常短信
     * @param phone
     * @param deviceName
     * @return
     
    public static boolean sendNotes1(String phone,String deviceName,String username,SmsConfig smsConfig){
    	   Map<String, String> params = new HashMap<>();
    	   params.put("devicename", deviceName);
    	   params.put("name", username);
		return send(phone,GetConfig.getSmsNotes1code(),params);
    	
    }*/
    
	/*
	 * public static void main(String[] args) { //
	 * System.out.println(sendByRegister("13128908197")); Map<String, String> params
	 * = new HashMap<>(); params.put("devicename", "8800001"); params.put("name",
	 * "lili");
	 * 
	 * System.out.println( send("13128908197",GetConfig.getSmsNotes1code(),params));
	 * // System.out.println( send("18607337285",map.get("notes1"),params));
	 * 
	 * }
	 */


    public  static void geUrl() throws IOException {
    	
/**
 * AccessKey ID:LTAIStrOEqKopj7i
Access Key Secret:RRoiiz5qYLpnnBA5uezQ9azcaTBjfK 
 * 短信模板CODE：
用户注册模板CODE：SMS_140850039
格式：验证码${code}，您正在注册成为新用户，感谢您的支持！


缺纸提醒模板CODE：SMS_140726817
格式：1
尊敬的${name}，您的纸巾机${devicename}剩余纸巾仅有${count}包，请尽快充纸。
格式：2
尊敬的${name}，您的纸巾机${devicename}发现故障，请及时检查。
 */
        //使用Jsoup 获取到网页元素
        Document doc= Jsoup.connect("http://www.mca.gov.cn/article/sj/xzqh/2018/201804-12/201804-06041553.html").get();
        //通过查看页面元素找到“行政区划代码 单位名称”的class为“xl7016293”
        //查找到元素
        Elements element=doc.getElementsByClass("xl7016293");
        int step = 0;
        StringBuffer sbf = new StringBuffer();
        //循环元素
        for (Element e : element) {
            if (step == 1){
                // e.text()获取元素的值
                sbf.append(String.format("\t%s%n", e.text()));
                step = 0;
            }else{
                sbf.append(e.text());
                step ++;
            }
        }
        String str = sbf.toString();
        System.out.print(str);
    }

   public static void main(String[] args) throws IOException {
       geUrl();
      Thread myThread = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    System.out.println("执行了一次 " + new Date().getTime());
                    try {
                        geUrl();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    try {
                        //Thread.sleep(毫秒); 1s = 1000ms
                        Thread.sleep(1000 * 60 * 60);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }); 
         myThread.start();
    }

}

















